import cv2
import numpy as np
import os
from glob import glob

# 生成字符画
arr = ["@", "W", "#", "$", "O", "E", "X", "C", "[", "(", "/", "?", "=", "^", "~", "_", ".", " "]
arr_len = arr.__len__() - 1


def trans_to_charImg(path):
    # 读图
    img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)

    # 初始化与原图一样尺寸的黑色图片
    h = np.size(img, 0)
    w = np.size(img, 1)
    res = np.ndarray([h, w])
    font = cv2.FONT_HERSHEY_SIMPLEX
    i_range = range(0, h, 10)
    i_range = i_range[0:-1]
    j_range = range(0, w, 10)
    j_range = j_range[0:-1]
    for i in i_range:
        for j in j_range:
            # 计数
            count = 0
            for x in range(10):
                for y in range(10):
                    if img[i+x,j+y] == 255:
                        count += 1

            t = arr[round((100-count) / 100 * arr_len)]
            # 绘制字符
            # 图片 文字 位置 字体 大小 颜色 粗细
            cv2.putText(res, t, (j, i), font, 0.5, color=(255, 255, 255))
    # 保存结果图
    save_filename = '%s.png' % (os.path.basename(filename).split('.')[0])
    print(save_filename)
    cv2.imwrite('images/charLineFrames/' + save_filename, res)

if __name__ == "__main__":
    # if not os.path.exists('edges'):
    #     os.makedirs('edges')
    file_list = glob('images/lineFrames_remove/*.png')
    for filename in file_list:
        trans_to_charImg(filename)